ydt1363 = {}

function ydt1363.GetCHKSUM(buf,buflen)
    
    --16进制转成字符串
    local strBuf = utils.Hex2Str(buf,buflen)
    local strBufLen = 2 * buflen

    --求和
    local sum = 0
    for index=1,strBufLen,1 do
        sum = sum + strBuf[index]
    end

    --累加值对65536取模，取反加1
    local chksum = utils.Not(math.modf(sum%65536),16)+1

    --换算成2个字节hex
    local chksumTable = {}
    local tmp = math.modf(chksum/256)
    table.insert(chksumTable,tmp)
    tmp = math.modf(chksum%256)
    table.insert(chksumTable,tmp)

    --换算成4个字节ascii
    local chksumStr = {}
    chksumStr = utils.Hex2Str(chksumTable,2)

    return chksumStr
end

function ydt1363.CheckCHKSUM(buf,bufLen)
    --求和
    local sum = 0
    --帧头7E要去掉，所以从2开始算
    for index=2,bufLen,1 do
        sum = sum + buf[index]
    end

    --累加值对65536取模，取反加1
    local chksum = utils.Not(math.modf(sum%65536),16)+1
    --print("chksum ".. string.format("%02X",chksum))

    --接收4个ASCII码CHKSUM转换2个字节Hex
    local chksumStr = {}
    chksumStr[1] = buf[bufLen+1]
    chksumStr[2] = buf[bufLen+2]
    chksumStr[3] = buf[bufLen+3]
    chksumStr[4] = buf[bufLen+4]
    local chksumTmp = utils.Str2Hex(chksumStr,4)
    local chksumHex = chksumTmp[1]*256+chksumTmp[2]
    --print("chksumHex ".. string.format("%02X",chksumHex))
    
    if(chksum == chksumHex) then
        return 0
    else
        return 1
    end
end

function ydt1363.GetLENGTHHex(LENID)
    --
    local LCHKSUM = math.modf((math.modf(LENID%65536/256)+math.modf(LENID%65536/16)+math.modf(LENID%256))%16)
    --累加值对16取模，取反加1
    LCHKSU = math.modf((utils.Not(LCHKSUM,16)+1)%16)

    local LENGTH = LCHKSU*4096+LENID

    --换算成2个字节hex
    local lengthTable = {}
    local tmp = math.modf(LENGTH/256)
    table.insert(lengthTable,tmp)
    tmp = math.modf(LENGTH%256)
    table.insert(lengthTable,tmp)

    return lengthTable
end

function ydt1363.GetLENGTH(length)

    local tmp = length[1]*256+length[2]

    local low = utils.And(tmp,0x0FFF) - 1
    local len = utils.And(utils.Not(low,16),0x0FFF)
    len = math.modf(len%65536)

    print("len "..string.format("%04X",len))
    
end

function ydt1363.CheckLCHKSUM(buf)

    local length = buf[1]*256+buf[2]
    
    local LCHKSUM = math.modf(utils.And(length,0xF000)/4096)
    --print("LCHKSUM " .. string.format("%01X",LCHKSUM))

    local LENID = utils.And(length,0x0FFF) 
    local LCHKSUMTmp = math.modf((math.modf(LENID%65536/256)+math.modf(LENID%65536/16)+math.modf(LENID%256))%16)
    LCHKSUMTmp = math.modf((utils.Not(LCHKSUMTmp,16)+1)%16)
    --print("LCHKSUMTmp " .. string.format("%01X",LCHKSUMTmp))

    local res = {}
    if(LCHKSUM == LCHKSUMTmp) then
        res[1] = 0
        res[2] = LENID
    else
        res[1] = 1
        res[2] = LENID
    end

    return res
end


return ydt1363